using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Web.Mail;

namespace IRL.Utilities
{
    

    /// <summary>
    /// Summary description for 
    /// </summary>
    /// 
    
    // Security
    public class Security
    {
        private const string UID_COOKIE = "irl_id"; // irl_id
        private const string ROLE_COOKIE = "irl_role"; // irl_role
        private string __redirectURL;
        private int __currentModule;
        private int __userID, __roleID;
        private int __permission;
        private bool __noRedirect;

        public Security()
        { }

        public Security(int module)
        {
            __currentModule = module;
            __userID = Convert.ToInt32(GetCookie(UID_COOKIE));
            __roleID = Convert.ToInt32(GetCookie(ROLE_COOKIE));
            __redirectURL = "login.aspx";
            __noRedirect = false;
        }

        private string GetCookie(string cookieName)
        {

            HttpCookie myCookie = HttpContext.Current.Request.Cookies[cookieName];
            if (myCookie != null)
            {
                return myCookie.Value;
            }
            else
            {
                return null;
            }
        }        

        public string RedirectURL
        {
            get { return __redirectURL; }
            set { __redirectURL = value; }
        }

        public void Authenticate()
        {
            object connStr = ConfigurationSettings.AppSettings["sqlConn"];
            using (SqlConnection conn = new SqlConnection(connStr.ToString()))
            {
                SqlCommand cmd = new SqlCommand("sp_GetPermission", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@irl_id", SqlDbType.Int).Value = __userID;
                cmd.Parameters.Add("@irl_role", SqlDbType.Int).Value = __roleID;
                cmd.Parameters.Add("@module", SqlDbType.Int).Value = __currentModule;
                conn.Open();
                __permission = (int)cmd.ExecuteScalar();
            }
            // Redirect if not authenticated
            if (__permission < 1 && __noRedirect == false)
            {
                HttpContext.Current.Response.Redirect(__redirectURL);
            }

        }

        public void Authenticate(bool NotRedirect)
        {
            __noRedirect = NotRedirect;
            Authenticate();
        }

        public bool IsReadOnly()
        {
            if (__permission == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsAuthorized(int requirePermission)
        {
            if (__permission < requirePermission)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    // Fill list class
    public class List
    {
        private static object connStr = ConfigurationSettings.AppSettings["sqlConn"];

        // Method:  fillChk
        // Created: 23-Jul-07
        // Action:  - Fill CheckboxList Control item
        public static void fillChk(CheckBoxList chk, string sql)
        {
            if (connStr != null)
            {
                SqlConnection conn = new SqlConnection(connStr.ToString());
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader dr;
                try
                {
                    conn.Open();
                    dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    chk.DataValueField = dr.GetName(0);
                    if (dr.FieldCount == 1)
                        chk.DataTextField = dr.GetName(0);
                    else
                        chk.DataTextField = dr.GetName(1);

                    chk.DataSource = dr;
                    chk.DataBind();
                }
                catch
                {
                    HttpContext.Current.Response.Redirect("unavailable.htm");
                }
                finally
                {
                    conn.Close();
                }

            }
        }

        // Method:  fillList
        // Action:  - Fill DropDownList item
        public static void fillList(DropDownList lst, string sql)
        {            
            try
            {
                //ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["sqlConnection"];
                //if (settings != null)
                //{
                //    //string connStr = "Server=(local); Database=irl; Uid=sa; Pwd=admin";
                //    string connStr = settings.ConnectionString.ToString();                

                if(connStr!=null)
                {
                    //ListItem li = new ListItem("", "-1");
                    using (SqlConnection conn = new SqlConnection(connStr.ToString()))
                    {
                        SqlCommand cmd = new SqlCommand(sql, conn);
                        conn.Open();
                        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                        lst.DataValueField = dr.GetName(0);
                        if (dr.FieldCount == 1)
                            lst.DataTextField = dr.GetName(0);
                        else
                            lst.DataTextField = dr.GetName(1);

                        lst.DataSource = dr;
                        lst.DataBind();
                        //lst.Items.Insert(0,li);                    
                    }
                }
            }
            catch 
            {                
                HttpContext.Current.Response.Redirect("unavailable.htm");
            }

        }

        // Function set DropDownList value
        public static void setList(DropDownList lst, string value)
        {
            foreach (ListItem li in lst.Items)
            {
                if (li.Value == value)
                {
                    li.Selected = true;
                    return;
                }
            }            
        }

        public static void setList(DropDownList lst, string value, string text)
        {
            foreach (ListItem li in lst.Items)
            {
                if (li.Value == value)
                {
                    li.Selected = true;
                    return;
                }
            }
            ListItem li_New = new ListItem(text, value);
            lst.Items.Insert(0, li_New);
        }
    }    

    // AutoNumber
    public class AutoNum
    {
        private int i;
        private int increment;

        // Constructor
        public AutoNum() { i = 1; increment = 1; }        
        public AutoNum(int start, int increment)
        {
            i = start;
            this.increment = increment;
        }

        // Get Next sequence
        public int GetNext()
        {
            int _r = i;
            i += increment;
            return _r;
        }

        // Reset value
        public void Reset()
        {
            i = 1;
            increment = 1;
        }

        // property Start
        public int Start 
        {
            get
            {
                return i;
            }
            set
            {
                i = value;
            }
        }

        //property increment
        public int Increment
        {
            get
            {
                return i;
            }
            set
            {
                increment = value;
            }
        }
        
    }

    // Fill Hash table
    public class Lookup
    {
        public static Hashtable Fill(string sql, SqlConnection conn)
        {
            Hashtable Temp = new Hashtable();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader dr;
            bool closedConn = false;
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
                closedConn = true;
            }
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Temp.Add(dr[0].ToString(), dr[1].ToString());
            }                        
            dr.Close();
            if (closedConn)
                conn.Close();
            return Temp;
        }

        public static string GetText(string sql, SqlConnection conn)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            bool closedConn = false;
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
                closedConn = true;
            }
            string value = (string)cmd.ExecuteScalar();
            if (closedConn)
                conn.Close();
            return (value == null ? "" : value);
        }
    }

    // Decoration
    public class Mics
    {
        public static void loadReminderCount(Literal elem)
        {
            string strScript = "<script language=\"javascript\">";
            object connStr = ConfigurationSettings.AppSettings["sqlConn"];
            int b_count, p_count;
            using (SqlConnection conn = new SqlConnection(connStr.ToString()))
            {
                SqlCommand cmd = new SqlCommand("sp_ListReminders", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@type", SqlDbType.VarChar, 10).Value = "Billing";
                cmd.Parameters.Add("@count", SqlDbType.Bit).Value = 1;
                conn.Open();
                b_count = (int)cmd.ExecuteScalar();
                // proposal reminder
                cmd.Parameters["@type"].Value = "Proposal";
                p_count = (int)cmd.ExecuteScalar();
                elem.Text = "<b>(" + (b_count + p_count) + ")</b>";
            }
            strScript += "menu2[0]=menu2[0].replace('%%COUNT%%', '(" + b_count + ")');";
            strScript += "menu2[1]=menu2[1].replace('%%COUNT%%', '(" + p_count + ")');";
            strScript += "<";
            strScript += "/";
            strScript += "script>";
            elem.Page.RegisterClientScriptBlock("RemindersCount",strScript);
        }

        public static void countReminder(Literal elem, string reminderType)
        {
            string market = "";
            if (HttpContext.Current.Request.Cookies["office"] != null)
                market = HttpContext.Current.Request.Cookies["office"].Value;
            object connStr = ConfigurationSettings.AppSettings["sqlConn"];
            using (SqlConnection conn = new SqlConnection(connStr.ToString()))
            {
                SqlCommand cmd = new SqlCommand("sp_ListReminders", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@userid", SqlDbType.Int).Value = HttpContext.Current.Request.Cookies["irl_id"].Value;
                cmd.Parameters.Add("@type", SqlDbType.VarChar, 10).Value = reminderType;
                if (market != "")
                    cmd.Parameters.Add("@market", SqlDbType.Int).Value = market;
                cmd.Parameters.Add("@count", SqlDbType.Bit).Value = 1;
                conn.Open();
                elem.Text = "(" + (int)cmd.ExecuteScalar() + ")";
            }
        }

        public static void MailSend(string To, string Subject, string Body)
        {
            MailMessage mailer = new MailMessage();
            mailer.From = "CMS - Administrator<chanmann@indochinaresearch.com>";
            mailer.To = To;
            mailer.Subject = Subject;
            mailer.BodyFormat = MailFormat.Html;
            mailer.Body = Body;
            // setting
            mailer.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); // Basic authentication
            mailer.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "chanmann");
            mailer.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "irlclim");
            // send mail
            SmtpMail.SmtpServer = "exchange";
            SmtpMail.Send(mailer);
        }

        //public string DivisionOf(double x, double y, string format)
        //{
        //    double result;
        //    if (y == 0)
        //    {
        //        result = 0;
        //    }
        //    else
        //    {
        //        result = x / y;
        //    }
        //    return String.Format("{0:"+ format +"}", result);
        //}
        
    }
}